# -*- encoding: utf-8 -*-
from openerp.osv import fields,osv
import openerp.addons.decimal_precision as dp
    
class mrp_bom(osv.osv):
    _inherit = 'mrp.bom'
    _order = 'seq_work,prod_code'
    def search(self, cr, user, args, offset=0, limit=None, order=None, context=None, count=False):
        #强制排序, 避免出错
        order='seq_work,prod_code'
        return super(mrp_bom,self).search(cr, user, args, offset, limit, order, context, count)  
    
    def compute_solder_cnt(self, cr, uid, ids, context=None):
        bom_data = {} #{prod_id:solder_cnt}
        for bom in self.browse(cr, uid, ids, context={'active_test':False}):
            if bom_data.has_key(bom.product_id.id):
                #已经计算过(可能是父BOM计算的时候已经自动计算过), 则不再执行
                continue
            self._calc_bom_solder(cr, uid, bom, bom_data, context=context)
        return True
    
    def to_state(self,cr,uid,ids,new_state,context=None):
        resu = super(mrp_bom, self).to_state(cr, uid, ids, new_state, context=context)
        if new_state == 'normal':
            self.compute_solder_cnt(cr, uid, ids, context=context)
        return resu
            
    #根据BOM计算某个BOM的焊点数
    def _calc_bom_solder(self, cr, uid, bom, bom_data, context=None):
        solder_cnt_total = 0
        for bom_line in bom.bom_lines:
            solder_cnt_total_line = 0.0
            if bom_line.product_id.supply_method == 'produce':
                #找到产品的BOM
                prod = bom_line.product_id
                bom_child = (prod.bom_id and prod.bom_id.product_id.id == prod.id) and prod.bom_id or None
                if not bom_child:
                    bom_id = self._bom_find(cr, uid, prod.id, prod.uom_id.id, properties=None)
                    if bom_id:
                        bom_child = self.browse(cr, uid, bom_id, context=context)
                if bom_child:
                    #递归调用
                    self._calc_bom_solder(cr, uid, bom_child, bom_data, context=context)
                else:
                    bom_data[prod.id] = 0.0
                #计算结果
                solder_cnt_total_line = bom_line.product_qty*bom_data.get(prod.id)
            else:
                solder_cnt_total_line = bom_line.product_qty*bom_line.product_id.solder_cnt
            #更新部件的总焊点数
            self.write(cr, uid, [bom_line.id], {'solder_cnt_total':solder_cnt_total_line})
            solder_cnt_total += solder_cnt_total_line   
                
        bom_data[bom.product_id.id] = solder_cnt_total
        #更新焊点信息
        self.write(cr, uid, [bom.id], {'solder_cnt_total':solder_cnt_total, 'solder_cnt':solder_cnt_total}, context=context)
        #johnw, 2017/03/16,更新工作量为焊点数(FSBC)
        vals = {'solder_cnt':solder_cnt_total}
        if bom.product_id.workload_type and bom.product_id.workload_type.id == 2:
            #使用'焊点数计算工作量'的产品, 自动更新工作量为焊点数
            vals['mrp_workload'] = solder_cnt_total
        self.pool.get('product.product').write(cr, uid, [bom.product_id.id], vals, context=context)
        
        return solder_cnt_total 
                
    def _get_prod(self, cr, uid, ids, context=None):
        result = {}
        for bom_id in self.pool.get('mrp.bom').search(cr, uid, [('product_id','in',ids),('state','!=','inactive')],context=context):
            result[bom_id] = True
        return result
                        
    _columns = {
        #部件使用
        'solder_cnt':fields.related('product_id','solder_cnt',type='integer', string='焊点数',readonly=1),
        #成品使用
        #johnw, 2017/02/18, 改为普通字段
        'solder_cnt_total':fields.integer('总焊点数', track_visibility='onchange'), 
        #部件工序号
        'seq_work':fields.integer('工序号'),
        #prod_code
        'prod_code':fields.related('product_id','default_code',type='char',size=128,
                store = {
                'product.product': (_get_prod, ['default_code'], 10),
            }),
        'write_date':fields.datetime('修改时间')
    }
#stock move, 增加焊点数
class stock_move(osv.osv):
    _inherit = 'stock.move'
    _columns = {
        #部件使用
        'solder_cnt':fields.integer('焊点数'),
        #成品使用
        #johnw, 2017/02/18, 改为普通字段
        'solder_cnt_total':fields.integer('总焊点数'), 
    }
       
    def _udpate_solder(self, cr, uid, ids, context=None):
        if ids:
            if isinstance(ids,(int,long)):
                ids = [ids]
            cr.execute('''
            update stock_move a
            set solder_cnt = b.solder_cnt,
                solder_cnt_total = b.solder_cnt*a.product_qty
            from product_product b
            where a.product_id = b.id
            and a.id in %s;            
            ''',(tuple(ids),))
        return True
        
    def write(self, cr, uid, ids, vals, context=None):
        resu = super(stock_move,self).write(cr, uid, ids, vals, context=context)  
        if 'product_qty' in vals:
            self._udpate_solder(cr, uid, ids, context=context)  
        return resu

    def create(self, cr, uid, vals, context=None):              
        id_new = super(stock_move,self).create(cr, uid, vals, context=context)
        self._udpate_price_total(cr, uid, [id_new], context=context)
        return id_new
'''
class product_product(osv.osv):
    _inherit = "product.product"
            
    _columns = {
        #bom_id is from dmp_mrp_bom_product
        #重定义mrp_workload, mrp_work_cost, 关联到bom_id的数据
        'mrp_workload': fields.related('bom_id','workload',string='总焊点数', type='integer', readonly=True),
        'mrp_work_cost': fields.related('bom_id','cost_work',string='加工成本', type='float', digits_compute=dp.get_precision('Product Price'), readonly=True),
        }
'''      
#BOM比较, 增加新的字段    
class bom_compare(osv.osv_memory):
    _inherit = 'bom.compare'
    _columns = {
        'compare_solder_cnt': fields.boolean('焊点数'),
        'compare_seq_work': fields.boolean('工序号'),
    }
    def _get_same_product_compare_fields(self, cr, uid, compare, context=None):
        field_names = super(bom_compare, self)._get_same_product_compare_fields(cr, uid, compare, context=context)
        if compare.compare_solder_cnt:
            field_names.update({'solder_cnt':'焊点数'})
        if compare.compare_seq_work:
            field_names.update({'seq_work':'工序号'})
        return field_names 
    